package cogbio.polFileGenerator;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;


public class MainGui extends JFrame implements ActionListener{

	/**
	 * 
	 */
	
	private static final String defPos = "<path-to-images>/Positive";
	private static final String defNeg = "<path-to-images>/Negative";
	
	private static final String helpFileName = "resources/help.txt";
	private static final long serialVersionUID = 2084369479896411642L;

	static private final String newline = "\n";
	
	private JTextField posPath, negPath, aPath, bPath, cPath, headerPath;
	private JTextField limitField,multipleField,sessionField;
	
	private JTextArea subjectNames;
	private JTextField cycleNrField,descField, genAmount;
	
	private String helpString = null;
	
	JCheckBox forcePositive = null;
	JCheckBox generateSubjectFiles = null;
	JCheckBox includeGen = null;
	
	JButton posButton, negButton, startButton, headerButton, aClassButton, bClassButton, cClassButton, helpButton, exitButton;
    JFileChooser fc;

	JTextArea log = null;
	
	MainGui(){
		PolFileGenerator.setParent(this);
		setTitle("Pol File Generator");
		//add(label);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new BorderLayout());
		
		readHelpFile();
		
		log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        @SuppressWarnings("unused")
		JScrollPane logScrollPane = new JScrollPane(log);

        //Create a file chooser
        fc = new JFileChooser();

        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        posButton = new JButton("Select the positive stimuli",null);
        posButton.addActionListener(this);
        
        
        posPath = new JTextField(30);
        posPath.setEditable(false);
        posPath.setText(defPos);
        //posPath.setText("C:/Users/Vegi/Documents/Univie/2011SS/CogBio/Images/Training/Positive");

        negPath = new JTextField(30);
        negPath.setEditable(false);
        negPath.setText(defNeg);
        //negPath.setText("C:/Users/Vegi/Documents/Univie/2011SS/CogBio/Images/Training/Negative");

        negButton = new JButton("Select the negative stimuli",null);
        negButton.addActionListener(this);
        
        //For layout purposes, put the buttons in a separate panel
        JPanel buttonPanelPos = new JPanel(); //use FlowLayout
        buttonPanelPos.add(posButton);
        buttonPanelPos.add(posPath);

        JPanel buttonPanelNeg = new JPanel(); //use FlowLayout
        buttonPanelNeg.add(negButton);
        buttonPanelNeg.add(negPath);

        aClassButton = new JButton("Select the A class",null);
        aClassButton.addActionListener(this);
        
        
        aPath = new JTextField(30);
        aPath.setEditable(false);
        aPath.setText("none");
        //aPath.setText("C:/Users/Martin Kysel/Documents/Univie/CogBio/Images/Generalization/Positive");
        

        bPath = new JTextField(30);
        bPath.setEditable(false);
        bPath.setText("none");
        //bPath.setText("C:/Users/Martin Kysel/Documents/Univie/CogBio/Images/Generalization/Negative");
        
        
        bClassButton = new JButton("Select the B class",null);
        bClassButton.addActionListener(this);
        
        //For layout purposes, put the buttons in a separate panel
        JPanel buttonPanelA = new JPanel(); //use FlowLayout
        buttonPanelA.add(aClassButton);
        buttonPanelA.add(aPath);

        
        
        JPanel buttonPanelB = new JPanel(); //use FlowLayout
        buttonPanelB.add(bClassButton);
        buttonPanelB.add(bPath);

        JPanel generalizationPanel = new JPanel();
        includeGen = new JCheckBox("Include test classes");
        includeGen.addActionListener(this);
        genAmount = new JTextField(2);
        genAmount.setText("8");
        JLabel generalizationLabel = new JLabel("Even Nr Trials");
        
        generalizationPanel.add(includeGen);
        generalizationPanel.add(generalizationLabel);
        generalizationPanel.add(genAmount);
        
        
        cPath = new JTextField(30);
        cPath.setEditable(false);
        cPath.setText("none");
        //bPath.setText("C:/Users/Martin Kysel/Documents/Univie/CogBio/Images/Generalization/Negative");
        
        
        cClassButton = new JButton("Select the C class",null);
        cClassButton.addActionListener(this);
        
        JPanel cPanel = new JPanel();
        cPanel.add(cClassButton);
        cPanel.add(cPath);
        
        
        
        JPanel additionalPanel = new JPanel();
        //additionalPanel.setBorder(new LineBorder(Color.BLACK));
        
        forcePositive = new JCheckBox("Force First Positive");
        additionalPanel.add(forcePositive);
        forcePositive.addActionListener(this);
        forcePositive.setSelected(true);
        
        additionalPanel.add(new JSeparator(SwingConstants.VERTICAL));

        
        JLabel limit = new JLabel("Cluster Size Limit:");
        additionalPanel.add(limit);
        
        limitField = new JTextField(2);
        limitField.setText("3");
        additionalPanel.add(limitField);
        
        JLabel multiple = new JLabel("Re-use Pool:");
        additionalPanel.add(multiple);
        
        multipleField = new JTextField(2);
        multipleField.setText("1");
        additionalPanel.add(multipleField);
        
        JLabel session = new JLabel("Session Size:");
        additionalPanel.add(session);
        
        sessionField = new JTextField(3);
        sessionField.setText("40");
        additionalPanel.add(sessionField);
        
        
        startButton = new JButton("Start Generation");
        //additionalPanel.add(startButton);
        startButton.addActionListener(this);

        helpButton = new JButton("Show Help");
        //additionalPanel.add(startButton);
        helpButton.addActionListener(this);

        exitButton = new JButton("Quit");
        //additionalPanel.add(startButton);
        exitButton.addActionListener(this);
        
        
        
        //JPanel buttonPanel = new JPanel();
        
        
        headerButton = new JButton("Select the header file",null);
        headerButton.addActionListener(this);
        
        
        headerPath = new JTextField(30);
        headerPath.setEditable(false);
        //headerPath.setText("C:/Users/Martin Kysel/Documents/header.txt");
        
        
        
        //For layout purposes, put the buttons in a separate panel
        JPanel headerPanel = new JPanel(); //use FlowLayout
        headerPanel.add(headerButton);
        headerPanel.add(headerPath);

        JPanel namesPanel = new JPanel();
        
        JLabel nameLabel = new JLabel("Subject Names:");
        subjectNames = new JTextArea(1,30);
        //subjectNames.setText("Niki, Bobbison, Verena, Claudia");
        
        
        namesPanel.add(nameLabel);
        namesPanel.add(subjectNames);
        
        
        JPanel additionalPanel2 = new JPanel();
        
        generateSubjectFiles = new JCheckBox("Generate Subject Files Also");
        generateSubjectFiles.setSelected(false);
        additionalPanel2.add(generateSubjectFiles);
        
        JLabel descLabel = new JLabel("Name:");
        additionalPanel2.add(descLabel);
        
        descField = new JTextField(10);
        descField.setText("snails");
        additionalPanel2.add(descField);
        
        
        JLabel cycleLabel = new JLabel("Nr of cycles:");
        additionalPanel2.add(cycleLabel);
        
        cycleNrField = new JTextField(2);
        cycleNrField.setText("10");
        additionalPanel2.add(cycleNrField);
        
        JPanel firstPanel = new JPanel(new GridLayout(3, 1));
        firstPanel.add(buttonPanelPos);
        firstPanel.add(buttonPanelNeg);
        firstPanel.add(additionalPanel);
        firstPanel.setBorder(new LineBorder(Color.BLACK));
        JScrollPane firstScroll = new JScrollPane(firstPanel);
        
        
        
        JPanel secondPanel = new JPanel(new GridLayout(4, 1));
        secondPanel.add(generalizationPanel);
        secondPanel.add(buttonPanelA);
        secondPanel.add(buttonPanelB);
        secondPanel.add(cPanel);
        secondPanel.setBorder(new LineBorder(Color.BLACK));
        JScrollPane secondScroll = new JScrollPane(secondPanel);

      
        JPanel thirdPanel = new JPanel(new GridLayout(3, 1));
        thirdPanel.add(additionalPanel2);
        thirdPanel.add(headerPanel);
        thirdPanel.add(namesPanel);
        thirdPanel.setBorder(new LineBorder(Color.BLACK));
        JScrollPane thirdScroll = new JScrollPane(thirdPanel);
        
        JPanel centerPanel = new JPanel(new GridLayout(1,2));
        centerPanel.add(secondScroll);
        centerPanel.add(thirdScroll);
        //Add the buttons and the log to this panel.
        //add(buttonPanelPos);
        //add(buttonPanelNeg);
        //add(additionalPanel);
        add(firstScroll, BorderLayout.PAGE_START);
        add(centerPanel, BorderLayout.CENTER);
        //add(thirdScroll, BorderLayout.EAST);
//        add(buttonPanelA);
//        add(buttonPanelB);
//        add(generalizationPanel);
//        add(cPanel);
      //Add the buttons and the log to this panel.
        //add(headerPanel, BorderLayout.PAGE_START);
        //add(namesPanel, BorderLayout.CENTER);
        //add(additionalPanel2, BorderLayout.PAGE_END);

        
        JPanel startPanel = new JPanel(new GridLayout(1, 3));
        startPanel.setBorder(new LineBorder(Color.BLACK));
        startPanel.add(startButton);
        startPanel.add(helpButton);
        startPanel.add(exitButton);
        
        add(startPanel,BorderLayout.PAGE_END);
        //add(logScrollPane, BorderLayout.PAGE_END);
		
        pack();
        setVisible(true);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new MainGui();

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		//Handle open button action.
		if (e.getSource() == exitButton){
			System.exit(0);
		}
		
		if (e.getSource() == helpButton){
			if (helpString!= null){
				JOptionPane.showMessageDialog(this, helpString);
			}
			else {
	        	JOptionPane.showMessageDialog(this, "No Help file found!");

			}
		}
		
        if (e.getSource() == posButton) {
            int returnVal = fc.showOpenDialog(MainGui.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                posPath.setText(file.getAbsolutePath());
    			posPath.setBackground(Color.white);
                log.append("Opening: " + file.getAbsolutePath() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());


		
        }
        if (e.getSource() == negButton) {
            int returnVal = fc.showOpenDialog(MainGui.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                negPath.setText(file.getAbsolutePath());
    			negPath.setBackground(Color.white);
                log.append("Opening: " + file.getAbsolutePath() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
		
        }
        
        if (e.getSource() == aClassButton) {
            int returnVal = fc.showOpenDialog(MainGui.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                aPath.setText(file.getAbsolutePath());

    			aPath.setBackground(Color.white);
                log.append("Opening: " + file.getAbsolutePath() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());


		
        }

        if (e.getSource() == bClassButton) {
            int returnVal = fc.showOpenDialog(MainGui.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                bPath.setText(file.getAbsolutePath());
    			bPath.setBackground(Color.white);
                log.append("Opening: " + file.getAbsolutePath() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());		
        }
        if (e.getSource() == cClassButton) {
            int returnVal = fc.showOpenDialog(MainGui.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                cPath.setText(file.getAbsolutePath());
                log.append("Opening: " + file.getAbsolutePath() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());

        }
        
        if (e.getSource() == startButton) {
        	System.out.println("start pressed");
        	boolean sthWrong = false;
        	
        	
        	if (includeGen.isSelected()){
        		if ((aPath.getText().equals("none") )){
        			aPath.setBackground(Color.red);
        			sthWrong = true;
        		}
        		int perSession = 0;
            	try {
            		perSession = Integer.parseInt(genAmount.getText());
            		if (perSession<1 || perSession%2!=0){
                		sthWrong=true;
                		genAmount.setBackground(Color.red);
                	} else {
                		genAmount.setBackground(Color.white);
                	}
            	}catch (NumberFormatException limitE){
            		//limitE.printStackTrace();
            		sthWrong=true;
            		genAmount.setBackground(Color.red);
            	}
            	
        		if (!sthWrong){ 
        			PolFileGenerator.includeGenFiles(aPath.getText(), bPath.getText(), cPath.getText(), perSession);
        			System.out.println("Including Gen Files");
        		}
        	} else {
        		aPath.setBackground(Color.white);
        		genAmount.setBackground(Color.white);
        	}
        	
        	
        	if(negPath.getText().equals(defNeg)){
        		sthWrong=true;
        		negPath.setBackground(Color.red);
        	}
        	if(posPath.getText().equals(defPos)){
        		sthWrong=true;
        		posPath.setBackground(Color.red);
        	}
        	
        	int limit = 0;
        	try {
        		limit = Integer.parseInt(limitField.getText());
        		if (limit<0){
            		sthWrong=true;
            		limitField.setBackground(Color.red);
            	} else {
            		limitField.setBackground(Color.white);
            	}
        	}catch (NumberFormatException limitE){
        		//limitE.printStackTrace();
        		sthWrong=true;
        		limitField.setBackground(Color.red);
        	}
        	
        	
        	int sessionSize = 0;
        	try {
        		sessionSize = Integer.parseInt((sessionField.getText()));
            	if (sessionSize<0 || sessionSize%2!=0){
            		sthWrong=true;
            		sessionField.setBackground(Color.red);
            	} else {
            		sessionField.setBackground(Color.white);
            	}
        	}catch (NumberFormatException limitE){
        		//limitE.printStackTrace();
        		sthWrong=true;
        		sessionField.setBackground(Color.red);
        	}
        	
        	int reuse = 0;
        	try {
        		reuse = Integer.parseInt(multipleField.getText());
            	if (reuse<1){
            		sthWrong=true;
            		multipleField.setBackground(Color.red);
            	} else {
            		multipleField.setBackground(Color.white);
            	}
        	}catch (NumberFormatException limitE){
        		//limitE.printStackTrace();
        		sthWrong=true;
        		multipleField.setBackground(Color.red);
        	}

        	
        	if (generateSubjectFiles.isSelected()){
        		String[] separated = subjectNames.getText().split(",");
        		if (separated.length==0){
        			separated = new String[1];
        			separated[0]="Default";
        		}
        		
        		String headerUrl = headerPath.getText();
        		String headerText = null;
        		if (headerUrl==null || headerUrl.equals("")){
        			sthWrong=true;
        			headerPath.setBackground(Color.red);
        		} else {
        			headerText = Utils.extractHeader(headerUrl);
        			
        			if (headerText==null){
        				headerPath.setBackground(Color.red);
        				sthWrong = true;
        			} else {
        				headerPath.setBackground(Color.white);
        				if (headerText.equals("empty")){
        					JOptionPane.showMessageDialog(
        							this,
        							"The Headerfile you provided is empty, consider selecting another one.");
        				}
        			}
        		}
        		int cycleNr = 0;
            	try {
            		cycleNr = Integer.parseInt(cycleNrField.getText());
                	if (cycleNr<1){
                		sthWrong=true;
                		cycleNrField.setBackground(Color.red);
                	} else {
                		cycleNrField.setBackground(Color.white);
                	}
            	}catch (NumberFormatException limitE){
            		//limitE.printStackTrace();
            		sthWrong=true;
            		cycleNrField.setBackground(Color.red);
            	}
        		
        		if (!sthWrong){
        			PolFileGenerator.multipleFiles(separated, cycleNr, headerText, descField.getText(),posPath.getText(), negPath.getText(), sessionSize,limit,forcePositive.isSelected(),reuse);
        		}
        	} else {
        		cycleNrField.setBackground(Color.white);
        		headerPath.setBackground(Color.white);
        	}
        	if (!sthWrong){
        		PolFileGenerator.generate(null, null, posPath.getText(), negPath.getText(), sessionSize,limit,forcePositive.isSelected(),reuse );
        		PolFileGenerator.resetGenOffset();
        		//forcePositive.isSelected()
        	}
        }

        
        if (e.getSource() == headerButton) {
            int returnVal = fc.showOpenDialog(MainGui.this);
            

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                headerPath.setText(file.getAbsolutePath());
                headerPath.setBackground(Color.white);
                log.append("Opening: " + file.getAbsolutePath() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());


		
        }


	}
	private void readHelpFile(){
		
		File file = new File(helpFileName);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e1) {
			try {
				file = new File(helpFileName.substring(helpFileName.indexOf("/")+1));
				br = new BufferedReader(new FileReader(file));
			} catch (FileNotFoundException e) {
				System.out.println("Help file not found");
			}
		}
		
		if (br!=null){

			StringBuffer sb = new StringBuffer();
			try {
				String temp = null;
				while ( (temp = br.readLine()) != null){
					sb.append(temp+"\n");

				}
				br.close();
				//System.out.println(sb.toString());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}	
			helpString= sb.toString();
		}	
	}
	
	public void showMessage(String message){
		JOptionPane.showMessageDialog(
				this,
				message);
	}
}